package com.athuahua.spzx.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.athuahua.spzx.properties.AlipayProperties;
import com.athuahua.spzx.service.AliPayService;
import com.athuahua.spzx.service.PaymentInfoService;
import com.athuahua.spzx.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author: huahua
 * @Date: 2024/8/23 0023
 * @Time: 16:19
 * @Description:
 */
@Tag(name = "支付接口")
@Controller
@RequestMapping("/api/order/alipay")
@Slf4j
public class AlipayController {

    @Resource
    private AliPayService aliPayService;

    @Resource
    private AlipayProperties alipayProperties;

    @Resource
    private PaymentInfoService paymentInfoService;


    //支付宝下单
    @GetMapping("submitAlipay/{orderNo}")
    @ResponseBody
    public Result<String> submitAlipay(@PathVariable("orderNo") String orderNo) {
        String from = aliPayService.submitAlipay(orderNo);



        return Result.success(from);
    }

    @Operation(summary="支付宝异步回调")
    @RequestMapping("callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        log.info("AlipayController...alipayNotify方法执行了...");
        //签名校验 数据是否具有合法性
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    alipayProperties.getAlipayPublicKey(),
                    AlipayProperties.charset,
                    AlipayProperties.signType);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 支付宝返回的交易状态
        String trade_status = paramMap.get("trade_status");
        if(signVerified){
            //签名校验成功
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
                // 正常的支付成功，我们应该更新交易记录状态
                paymentInfoService.updatePaymentStatus(paramMap);
                return "success";
            }

        }else{
            //签名校验失败
            return "failure";

        }
        return "failure";
    }



    @Operation(summary="测试用例")
    @GetMapping("test")
    public Result alipayNotify(){
        paymentInfoService.testUpdatePaymentStatus();
        return Result.success("success");
    }



}
